package cc.booku.owlbox.CollectionStation_norm;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.timmy.tdialog.TDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.VideoPlayer.PlayerActivity;

public class CS_FileScannerActivity extends AppCompatActivity {


    private Toolbar Toolbar;
    private TextView Fromfileurl, EditClean, EditSave;
    private EditText Filedetails;
    private LinearLayout FileEditLayout;
    private GridView collectionstationGridview;
    private TDialog tDialog;
    private static final int WHAT_LOADING = 0;

    private List<CollectionStation_C> collectionStation_cList = new ArrayList<CollectionStation_C>();
    // private String DefaultPort = "/storage/emulated/0/OwlDatabase/DefaultPort.txt";
    private String filePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cs_file_scanner);


        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        //FINDEBYID
        LoadControl();
        //打开文件解析
        RXDMainActivity();

    }

    private void LoadToolbar() {
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
//        Toolbar.inflateMenu(R.menu.menu_user);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_edit:
                        if (FileEditLayout.getVisibility() == View.VISIBLE) {
                            FileEditLayout.setVisibility(View.GONE);
                        } else FileEditLayout.setVisibility(View.VISIBLE);

                        break;
//                    case R.id.action_code:
//                        //打开窗口修改地址
//                        DialogM3u8();
//                        break;

                }
                return true;
            }
        });
    }


    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu_norm_port, menu);//toolbar添加menu菜单
        return true;
    }


//
//    private void DialogM3u8() {
//
//        new TDialog.Builder(getSupportFragmentManager())
//                .setLayoutRes(R.layout.tdialog_upprofile)
//                .setScreenWidthAspect(this, 1.0f)
//                .setGravity(Gravity.CENTER)
//                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
//                    @Override
//                    public void bindView(BindViewHolder bindViewHolder) {
//                        bindViewHolder.setText(R.id.editText, FileoOperations.readAssetsTxt(CS_FileScannerActivity.this,"TxtData/DefaultPort"));
//                    }
//                })
//                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
//                .setOnViewClickListener(new OnViewClickListener() {
//                    @Override
//                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
//
//                        EditText editText = viewHolder.getView(R.id.editText);
//                         String content = editText.getText().toString().trim();
//                        switch (view.getId()) {
//                            case R.id.btn_cancel:
////                                if (FileoOperations.fileIsExists(DefaultPort)) {
////                                    FileoOperations.writeAssignTxt(DefaultPort,FileoOperations.readAssetsTxt(CS_FileScannerActivity.this,"TxtData/DefaultPort"));
////                                    Toast.makeText(CS_FileScannerActivity.this, "默认解析口："+FileoOperations.readFromSDFile(CS_FileScannerActivity.this,DefaultPort), Toast.LENGTH_SHORT).show();
////                                   // WaitingRefresh();
////                                } else {
////                                    Toast.makeText(CS_FileScannerActivity.this, "编辑失败", Toast.LENGTH_SHORT).show();
////                                }
//                                tDialog.dismiss();
//                                break;
//                            case R.id.btn_affirm:
//                                //String DefaultPort =  FileoOperations.readFromSDFile(CS_FileScannerActivity.this,"/storage/emulated/0/OwlDatabase/DefaultPort.txt");
//                               // editText.setText(DefaultPort);
//
//                                //Log.d("Filedetails", "Filedetails.toString()" + DefaultPort);
//                                //重新写入数据到文件
//                                if (FileoOperations.fileIsExists(DefaultPort)) {
//                                    //先输入空字符串，清空文件
//                                    //FileoOperations.writeAssignTxt(Fromfileurl.getText().toString(), "");
//                                    // Log.d("Filedetails", "Filedetails.toString()" + Filedetails.getText().toString());
//                                    //写入修改后的字符
//                                    FileoOperations.writeAssignTxt(DefaultPort,content);
//                                    Toast.makeText(CS_FileScannerActivity.this, "解析口更换为："+content, Toast.LENGTH_SHORT).show();
//                                    //等待刷新
//                                    //WaitingRefresh();
//                                } else {
//                                    Toast.makeText(CS_FileScannerActivity.this, "编辑失败", Toast.LENGTH_SHORT).show();
//                                }
//                                tDialog.dismiss();
//                                break;
//
//                        }
//
//
//                    }
//                })
//
//                .create()
//                .show();
//    }


    private void LoadControl() {

        Fromfileurl = (TextView) findViewById(R.id.fromfileurl);
        //Fromfileurl.setText(filePath);
        Filedetails = (EditText) findViewById(R.id.filedetails);
        EditClean = (TextView) findViewById(R.id.tv_editclean);
        EditSave = (TextView) findViewById(R.id.tv_editsave);

        FileEditLayout = (LinearLayout) findViewById(R.id.fileedit_layout);
        collectionstationGridview = (GridView) findViewById(R.id.gv_collectionstation);
        //控件监听
        ControlsListen();
    }

    private void ControlsListen() {
        EditClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Filedetails.setText("");
            }
        });
        EditSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Log.d("Fromfileurl", "Fromfileurl.toString()-----" + Fromfileurl.getText().toString());
                //重新写入数据到文件
                if (FileoOperations.fileIsExists(Fromfileurl.getText().toString())) {
                    //先输入空字符串，清空文件
                    //FileoOperations.writeAssignTxt(Fromfileurl.getText().toString(), "");
                    // Log.d("Filedetails", "Filedetails.toString()" + Filedetails.getText().toString());
                    //写入修改后的字符
                    FileoOperations.writeAssignTxt(Fromfileurl.getText().toString(), Filedetails.getText().toString());
                    //隐藏
                    FileEditLayout.setVisibility(View.GONE);
                    //等待刷新
                    WaitingRefresh();
                } else
                    Toast.makeText(CS_FileScannerActivity.this, "编辑失败", Toast.LENGTH_SHORT).show();

            }
        });

    }

    //等待刷新函数
    private void WaitingRefresh() {
        Toast.makeText(CS_FileScannerActivity.this, "编辑成功", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // finish();
                collectionStation_cList.clear();
                RXDMainActivity();
            }
        }, 2000);
        // onCreate(null);//调用此方法刷新页面

    }

    private void RXDMainActivity() {

        loadingDialog();

        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String SpecifiedFile = bundle.getString("SpecifiedFile");

        Fromfileurl.setText(SpecifiedFile);

        //读取的文件数据：FileoOperations.readFromSDFile(this,SpecifiedFile)
        Filedetails.setText(FileoOperations.readFromSDFile(this, SpecifiedFile));

        try {
            //尝试解析代码
            FastJson_analysis(SpecifiedFile);
        } catch (Exception e) {
            //异常处理
            Toast.makeText(CS_FileScannerActivity.this, "数据解析错误", Toast.LENGTH_SHORT).show();
        }

    }


    public void loadingDialog() {
        tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_loading)
                .setHeight(300)
                .setWidth(300)
                .setCancelableOutside(false)
                .create()
                .show();
        handler.sendEmptyMessageDelayed(WHAT_LOADING, 3 * 1000);

    }


    private CollectionStation_C collectionStationC;
    private CollectionStation_A collectionStationA;

    //fastjson解析json--来自aliyun的开源库
    private void FastJson_analysis(String str) {
//指定文件内容转换为SpecifiedFile------string类型
        String SpecifiedFile = FileoOperations.readFromSDFile(this, str);
//使用fastJson解析Json
        List<CollectionStation_C> collectionStationCList = JSON.parseArray(SpecifiedFile.toString(), CollectionStation_C.class);
        for (CollectionStation_C normVideo : collectionStationCList) {
            collectionStationC = new CollectionStation_C();

//    vod_score  ---评分
//    vod_name	----影片名称
//    vod_class  ----类型
//    vod_pic ----图片地址
//    vod_play_url --视频地址
//    vod_add_time  ---添加日期

//    vod_actor ---演员
//    vod_director ---导演
//    vod_blurb  ---影片简介
//    vod_area  ---地区
//    vod_year  ---上映年份
//    vod_lang  ---语言

            String vod_score = normVideo.getVod_score();
            String vod_name = normVideo.getVod_name();
            String vod_class = normVideo.getVod_class();
            String vod_add_time = normVideo.getVod_add_time();
            String vod_pic = normVideo.getVod_pic();
            String vod_play_url = normVideo.getVod_play_url();

            String vod_actor = normVideo.getVod_actor();
            String vod_director = normVideo.getVod_director();
            String vod_blurb = normVideo.getVod_blurb();
            String vod_area = normVideo.getVod_area();
            String vod_year = normVideo.getVod_year();
            String vod_lang = normVideo.getVod_lang();
            String vod_id = normVideo.getVod_id();

            // Log.d("ImageviewHolder", "显示图片url======" + vod_pic);

            collectionStationC.setVod_score("评分:" + vod_score);
            collectionStationC.setVod_name(vod_name);
            collectionStationC.setVod_class(vod_class + "#" + vod_year + "#" + vod_area + "#" + vod_lang + "#" + vod_id);
            collectionStationC.setVod_add_time(vod_add_time);
            collectionStationC.setVod_pic(vod_pic);
            collectionStationC.setVod_pic_url(vod_pic);
            collectionStationC.setVod_play_url(vod_play_url);
            collectionStationC.setVod_value_add("导演：" + vod_director + "\n演员：" + vod_actor + "\n类型：" + vod_class + "\n上映地区：" + vod_area + "\n上映年份：" + vod_year + "\n语言：" + vod_lang + "$片名：" + vod_name + "\n剧情简介：" + vod_blurb);


            collectionStation_cList.add(collectionStationC);


        }
        Message msg = new Message();
        msg.what = 2;
        handler.sendMessage(msg);//用activity中的handler发送消息

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


                case 2:
                    listClickListener((ArrayList<CollectionStation_C>) collectionStation_cList);
                    break;

                case WHAT_LOADING:
                    if (tDialog != null) {
                        tDialog.dismiss();
                    }
                    return;
            }
        }
    };


    public void listClickListener(ArrayList<CollectionStation_C> collectionStationC) {


        collectionStationA = new CollectionStation_A(R.layout.collectionstation_item, this, collectionStationC);

        collectionstationGridview.setAdapter(collectionStationA);
        collectionstationGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //Toast.makeText(getContext(), "Click ++ item" + i, Toast.LENGTH_SHORT).show();
                final TextView vod_class1 = (TextView) view.findViewById(R.id.vod_class);
                final TextView vod_score1 = (TextView) view.findViewById(R.id.vod_score);
                final TextView vod_name1 = (TextView) view.findViewById(R.id.vod_name);
                final TextView vod_add_time1 = (TextView) view.findViewById(R.id.vod_add_time);
                final TextView vod_play_url1 = (TextView) view.findViewById(R.id.vod_play_url);
                final TextView vod_value_add1 = (TextView) view.findViewById(R.id.vod_value_add);
                final TextView vod_pic_url1 = (TextView) view.findViewById(R.id.vod_pic_url);

                String vod_class2 = vod_class1.getText().toString();
                String vod_score2 = vod_score1.getText().toString();
                String vod_name2 = vod_name1.getText().toString();
                String vod_add_time2 = vod_add_time1.getText().toString();
                String vod_play_url2 = vod_play_url1.getText().toString();
                String vod_value_add2 = vod_value_add1.getText().toString();
                String vod_pic_url2 = vod_pic_url1.getText().toString();

                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("vod_class", vod_class2);
                bundle.putString("vod_score", vod_score2);
                bundle.putString("vod_name", vod_name2);
                bundle.putString("vod_add_time", vod_add_time2);
                bundle.putString("vod_play_url", vod_play_url2);
                bundle.putString("vod_value_add", vod_value_add2);
                bundle.putString("vod_pic", vod_pic_url2);
                intent.putExtras(bundle);
                intent.setClass(CS_FileScannerActivity.this, PlayerActivity.class);
                startActivity(intent);


            }
        });

    }

}
